有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

替换文件中包含的文件名,并使用java将文件重命名为新名称

我一直试图通过在给定文件夹中查找并替换其名称中的子字符串来重命名这些文件和文件夹。此外,文件名也包含在其内容中。我需要换个新名字

例如:

Change "XXX" to "KKK" in all the files and folder names and also in file contents:

Original file name: 0001_XXX_YYY_ZZZ.txt

New file name: 0001_KKK_YYY_ZZZ.txt

下面是我正在使用的代码

当我在不调用函数replaceText()的情况下运行以下代码时,它将重命名文件和文件夹。但是,当我试图更改文件的文本,然后重命名文件和文件夹时;文件内容已更改,但重命名文件和文件夹失败

请帮忙

public class FindReplaceAnywhere {

    public static void main(String[] args) {
        String find = "XXX";
        String replace = "KKK";
        String baseLoc = "D:\\0001_XXX_YYY_ZZZ";

        FindReplaceAnywhere obj = new FindReplaceAnywhere();

        File baseLocObj = new File(baseLoc);
        LinkedList<File> baseFolderList = new LinkedList<File>();

        // Add base folder object to list
        baseFolderList.add(baseLocObj);

        // Get list of files in the folder
        for(File file: baseLocObj.listFiles()) {
            baseFolderList.add(file);
        }

        // Rename the files, folders & contents of files
        obj.rename(baseFolderList, find, replace);
    }

    public void rename(LinkedList<File> fileList, String find, String replace) {
        String tempStr = null;
        int beginIndex = 0;
        int endIndex = 0;
        File tempFile;

        System.out.println(">>> Batch Rename Process Begins >>>\n");

        for(File aFile:fileList) {
            // If Object is File, change the text also
            if(aFile.isFile()) {
                replaceText(aFile,find,replace);
            }
        }
    
        for(File aFile: fileList) {
            System.out.println("Processing>>>");
            System.out.println(aFile.getPath());
            if(aFile.getName().contains(find)) {
                // Get the name of File object
                beginIndex = aFile.getPath().length() - aFile.getName().length();
                endIndex = aFile.getPath().length();
                tempStr = aFile.getPath().substring(beginIndex, endIndex);
                tempStr = tempStr.replace(find, replace);
            }
            else {
                System.out.println("Error: Pattern not found\n");
                continue;
            }
            tempFile = new File(aFile.getParentFile(),tempStr);

            boolean success = aFile.renameTo(tempFile);
            if(success) {
                System.out.println("File Renamed To: "+tempFile.getName());
            }
            else {
                System.out.println("Error: Rename Failed\nPossible Cause: File is open in another application");
            }
            System.out.println("");
        }
    }

    /**
     * Replace the text of file if it contains filename
     */
    public void replaceText(File file, String find, String replace) {
        String fullText = "";
        String line = "";
        String fileName = "";
        String replaceName = "";

        BufferedReader in;
        BufferedWriter out;

        // Read the file contents
        try {
            in = new BufferedReader(new FileReader(file));
            while((line = in.readLine()) != null) {
                fullText+=line+"\n";
            }
        }
        catch(FileNotFoundException e) {
            e.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    
        // Replace the text of file
        fileName = file.getName().substring(0, file.getName().indexOf("."));
        replaceName = fileName.replace(find, replace);
        fullText = fullText.replace(fileName, replaceName);

        // Write the replaced text to file
        try {
            out = new BufferedWriter(new FileWriter(file));
            out.write(fullText);
            out.close();
        }
        catch(FileNotFoundException e) {
            e.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }       
    }
}

共 (1) 个答案

  1. # 1 楼答案

    在读取输入(in)文件后,看起来您并没有关闭该文件,这将使该文件保持打开状态-在*nix下重命名应该仍然有效,但在Windows下会失败:

    • 使用finally块确保资源已关闭。。但只有在你确信它被打开之后

    在此期间,请允许我建议对代码进行另一项更改:

    • 将“声明”移动到代码中可以进行声明的最后一点。。避免提前申报。在这种情况下,inout都不必要地提前声明。还有其他的,;我把这个留给你去解决

    因此,对于输入文件:

        // Read the file contents
        try {
            BufferedReader in = new BufferedReader(new FileReader(file));
            // If you got this far, the file is open...
            // use try/finally to ensure closure.
            try {
                while((line = in.readLine()) != null) {
                    fullText+=line+"\n";
                }
            }
            finally {
              in.close();
            }
        }
        catch(FileNotFoundException e) {
            e.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    

    对于输出文件:

        // Write the replaced text to file
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            try {
                out.write(fullText);
            }
            finally {
                out.close();
            }
        }
        catch(FileNotFoundException e) {
            e.printStackTrace();
        }
        catch(IOException e) {
            e.printStackTrace();
        }